#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <time.h>
#include <fcntl.h>
#include "socket_util.h"

int init_sock() {
    //创建套接字
    int sock = socket(AF_INET, SOCK_STREAM, 0);

    //向服务器（特定的IP和端口）发起请求
    struct sockaddr_in serv_addr;
    new_sockaddr(&serv_addr, "127.0.0.1", 12355);
    (void)connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
    return sock;
}

const enum GAME_MSG actions[3] = {
    GAME_MSG_CLOTH, GAME_MSG_SCISSORS, GAME_MSG_STONE};

enum GAME_MSG rand_action() {
    int fd;
    unsigned long seed;
    fd = open("/dev/urandom", 0);
    if (fd < 0 || read(fd, &seed, sizeof(seed)) < 0) {
        printf("[ERROR]: Could not load seed from /dev/urandom");
        seed = time(0);
    }
    if (fd >= 0) close(fd);
    //设置随机种子
    srand(seed);
    return actions[rand() % 3];
}

int main(){
    int sock = init_sock();
    
    for(int is_over = 1; !is_over;) {
        enum GAME_MSG msg = recv_game_msg(sock);
        enum GAME_MSG action;
        switch(msg) {
            case GAME_MSG_START_ROUND:
                action = rand_action();
                send_game_msg(sock, action);
                enum WINNER winner = get_winner(action, recv_game_msg(sock));
                switch (winner) {
                    case PLAYER_0:
                        printf("[Game Info]: You win this round!");
                        print_endl();
                        break;
                    case PLAYER_1:
                        printf("[Game Info]: You lost this round!");
                        print_endl();
                        break;
                    case DRAW:
                        printf("[Game Info]: This round draws.");
                        print_endl();
                        break;
                }
                break;
            case GAME_MSG_FINAL_DRAW:
                printf("[Game Info]: Finally, it draws!");
                print_endl();
                is_over = 1;
                break;
            case GAME_MSG_FINAL_WIN:
                printf("[Game Info]: Finally, you win!");
                print_endl();
                is_over = 1;
                break;
            case GAME_MSG_FINAL_LOST:
                printf("[Game Info]: Finally, you lost!");
                print_endl();
                is_over = 1;
                break;
            default:
                printf("[ERROR]: Recived Unknown Message From Server!");
                print_endl();
                break;
        }
    }

    //关闭套接字
    close(sock);

    return 0;
}